using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 默认属性提取实现（规则法），无外部依赖，保障基础可用性
    /// </summary>
    public class BuiltInAttributeExtractionService : IAttributeExtractionService
    {
        private readonly ILogger<BuiltInAttributeExtractionService> _logger;

        public BuiltInAttributeExtractionService(ILogger<BuiltInAttributeExtractionService> logger)
        {
            _logger = logger;
        }

        public Task<Dictionary<string, object>> ExtractAsync(string text, string? hintTag = null)
        {
            var attrs = new Dictionary<string, object>();
            try
            {
                var t = text ?? string.Empty;
                var lower = t.ToLowerInvariant();

                // 1) tag 推断（若未显式提供）
                string tag = hintTag ?? InferTag(lower);
                attrs["tag"] = tag;

                // 2) 基础实体粗提取（角色名/地名），非常保守
                var characters = ExtractPossibleNames(t).Take(5).ToArray();
                if (characters.Length > 0) attrs["characters"] = characters;

                var worlds = ExtractPossiblePlaces(t).Take(5).ToArray();
                if (worlds.Length > 0) attrs["world_entities"] = worlds;

                // 3) 时间戳
                attrs["createdAt"] = DateTime.UtcNow.ToString("o");
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "属性提取失败（使用最小集返回）");
            }

            return Task.FromResult(attrs);
        }

        private static string InferTag(string lower)
        {
            bool has(string s) => lower.Contains(s.ToLowerInvariant());
            if (has("润色") || has("风格")) return "preference";
            if (has("章节细纲") || has("细纲")) return "character"; // 细纲优先角色
            if (has("大纲")) return "summary";
            if (has("冲突") || has("矛盾")) return "conflict";
            if (has("世界观") || has("设定") || has("背景")) return "world";
            if (has("继续") || has("续写") || has("上一段")) return "summary";
            if (has("角色") || has("人物")) return "character";
            return "summary";
        }

        private static IEnumerable<string> ExtractPossibleNames(string text)
        {
            // 简单规则：匹配两个及以上汉字的人名样式（启发式）
            var m = Regex.Matches(text, "[\u4e00-\u9fa5]{2,4}");
            foreach (Match mm in m)
            {
                var v = mm.Value;
                if (!string.IsNullOrWhiteSpace(v)) yield return v;
            }
        }

        private static IEnumerable<string> ExtractPossiblePlaces(string text)
        {
            // 简单规则：包含“城/宗/门/谷/国/洲/镇”的词
            var m = Regex.Matches(text, "[\u4e00-\u9fa5]{1,5}(城|宗|门|谷|国|洲|镇)");
            foreach (Match mm in m)
            {
                var v = mm.Value;
                if (!string.IsNullOrWhiteSpace(v)) yield return v;
            }
        }
    }
}

